package com.pet.server.ext.util.nuomi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.pet.server.ext.Logger;
import com.pet.server.ext.util.HttpClientUtils;
import com.pet.server.ext.util.JsonUtil;
import com.pet.server.ext.util.Pinyin;
import com.pet.server.ext.util.StringUtil;


public class NuomiClient {

	private static final Logger logger = Logger.getLogger(NuomiClient.class);
	private static final String SEARCH_DEALS = "http://apis.baidu.com/baidunuomi/openapi/searchdeals";
	private static final String DEAL_DETAILS = "http://apis.baidu.com/baidunuomi/openapi/dealdetail";
    private static final String SHOP_INFO="http://apis.baidu.com/baidunuomi/openapi/shopinfo";
	private static final String CITIES="http://apis.baidu.com/baidunuomi/openapi/cities";
	private static JSONObject citiesJson=null;
	private static final String API_KEY  = "f1f675ad47015d2e3c6dced5737ced19";
    private static String defaultCityId="100010000";
	public static void main(String[] args){
		//JSONObject obj = NuomiClient.searchDeals("100010000","116.4374,39.8719",null,1,20,"8000");
		String cityId = findCityId("龙岩市");
		System.out.println(cityId);
	}
    
	public static JSONObject searchDeals(String city_name,String location,String keyword,Integer pageNo,Integer pageSize,String radius){
		String cityId = findCityId(city_name);
		return searchDeals2api(cityId, location, keyword, pageNo, pageSize, radius);
	}
	public static JSONObject dealDetail(String deal_id){
		 Map<String, String> map = new HashMap<String, String>();
		    map.put("deal_id", deal_id);//城市id
		    String httpArg = gethttpArg(map);	    
		    String res = NuomiClient.request(DEAL_DETAILS, httpArg);
		    try{
			    return JSONObject.fromObject(res);
		    }catch(Exception e){
		    	return null;
		    }	 
	}
	public static JSONObject shopinfo(String shop_id){
		 Map<String, String> map = new HashMap<String, String>();
		    map.put("shop_id", shop_id);//城市id
		    String httpArg = gethttpArg(map);	    
		    String res = NuomiClient.request(SHOP_INFO, httpArg);
		    try{
			    return JSONObject.fromObject(res);
		    }catch(Exception e){
		    	return null;
		    }	 
	}
	
	
	
	public static String findCityId(String city){
		if(StringUtil.isEmpty(city)){
			return defaultCityId;
		}
		city = city.replaceAll("(省|市|区|县)","");
		Pinyin py = new Pinyin();
		String city_pinyin = py.getAllPY(city);
		if(null==citiesJson){
			cities();
		}
		JSONArray array = JsonUtil.getValue(citiesJson, "cities", JSONArray.class);
		for(int index=0;index<array.size();index++){
			JSONObject jo = array.getJSONObject(index);
			if(StringUtil.equals(city_pinyin, jo.getString("city_pinyin"))){
				return jo.getString("city_id");
			}
		}
		return defaultCityId;
	}
	public static void cities(){
		String cities = request(CITIES, "");
		try{
			JSONObject json = JSONObject.fromObject(cities);
			Integer errno = JsonUtil.getValue(json,"errno", Integer.class);
		    if(errno==0){
		    	citiesJson=json;
		    }
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static JSONObject  searchDeals2api(String cityId,String location,String keyword,Integer pageNo,Integer pageSize,String radius){
	    Map<String, String> map = new HashMap<String, String>();
	    map.put("city_id", cityId);//城市id
	    map.put("cat_ids", "316");//分类id
	    map.put("subcat_ids", "367");//二级分类id
	    map.put("district_ids", "");//行政区id
	    map.put("bizarea_ids", "");//商圈id
	    map.put("location", location);//经纬度
	    map.put("keyword", "");//关键词
	    map.put("radius", radius);//范围米
	    map.put("sort", "5");//0:综合排序 1：价格低优先， 2：价格高优先， 3：折扣高优先， 4：销量高优先， 5：用户坐标距离近优先， 6：最新发布优先,8:用户评分高优先
	    map.put("page", StringUtil.dealNull(pageNo));//页码
	    map.put("page_size", StringUtil.dealNull(pageSize));//页条数
	    //map.put("is_reservation_required", "0");
	    
	    String httpArg = gethttpArg(map);	    
	    String res = NuomiClient.request(SEARCH_DEALS, httpArg);
	    try{
		    return JSONObject.fromObject(res);
	    }catch(Exception e){
	    	return null;
	    }	    
	}
	public static String gethttpArg(Map<String, String> map){
		boolean b=true;
		StringBuffer sbuf = new StringBuffer();
		for(Entry<String, String> en:map.entrySet()){
			String key = en.getKey();
			String value =  StringUtil.encode(en.getValue(), "utf-8");
			if(!StringUtil.isEmpty(value)){
				String param = key+"="+value;
				sbuf.append(b?param:"&"+param);
	            if(b){
	            	b=false;
	            }		
			}
		}
		return sbuf.toString();
	}
	
	public static String request(String httpUrl, String httpArg) {
		logger.logInfo(httpUrl+"?"+httpArg);
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();
	    httpUrl = httpUrl + "?" + httpArg;

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("GET");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey",  API_KEY);
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    logger.logInfo(result);
	    return result;
	}
	
}
